import json
import os

import aiofiles
import falcon

import App_setting as setting
from WebBackend.middleware.virtualWorldGate_Chuche import login_require
from WebBackend.utils.executeCMD import execute_cmd_async
from WebBackend.utils.readFile import read_file_async


class ThingsAPI:
    async def on_get(self, req: falcon.Request, resp: falcon.Response):
        name = req.params.get('name')
        if name == 'version':
            resp.text = await handle_version()
        elif name == 'b':
            pass
        elif name == 'c':
            pass
        else:
            file = os.path.join(setting.path.dir_project_root, '57971627.jpg')
            resp.stream = await aiofiles.open(file, 'rb')
            resp.content_type = 'image/jpg'

    @falcon.before(login_require)
    async def on_post(self, req, resp):
        text = await execute_cmd_async("ping www.baidu.com -c 3", 'str')
        resp.text = text

    @staticmethod
    async def sink_redirect(req, resp):
        resp.location = '/'
        resp.status = falcon.HTTP_301


async def handle_version() -> str:
    j = await read_file_async(os.path.join(setting.path.dir_project_root, 'version.json'), 'str')
    if not j:
        return 'x.x.x'
    else:
        j = json.loads(j)
        return j['frontend_version']
